package com.yk._05Callable可获取线程结果;

import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class _01Callable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        Resource resource = new Resource();
        //1先new一个callable对象
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                TimeUnit.SECONDS.sleep(1);
                return resource.getString();
            }
        };
        //2 然后实用futrueTask包装callable
        FutureTask<String> futureTask = new FutureTask(callable);
        //3将futuretask交给Thread执行


        new Thread(futureTask, "线程A").start();
        // 1.这里可能会返回结果，或者抛出异常，如果Callable线程阻塞 这里获取结果也会阻塞，从而导致本线程(这里是main线程)阻塞
        // 2.结果可能缓存
        String res = futureTask.get();
        System.out.println("res = " + res);
    }


}
class Resource{
    public String getString(){
        return UUID.randomUUID().toString().substring(0,5);
    }
}

